//
//  RecordSplitViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordSplitViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "EZAudioFile.h"
#import "FileManager.h"
#import "CustomAlertView.h"
#import "RecordEditSpectrumCollectionViewCell.h"
#import "LocalRecordModel.h"

@interface RecordSplitViewController ()<AVPlayerDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    CGFloat spectrumGridWidth;
    BOOL isDragging;
    NSMutableArray *dataMutArr;
    LocalRecordModel *selectModel;
    
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (nonatomic, strong) CustomLineView *line;

@end

@implementation RecordSplitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"拆分";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(donePress) forControlEvents:UIControlEventTouchUpInside];
    
    dataMutArr = [NSMutableArray array];
    [dataMutArr addObject:[self.model copy]];
    selectModel = [dataMutArr firstObject];
    selectModel.isSelected = YES;
    [self seeAudio:selectModel];
    
    [self initView];

    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    [AVPlayerManager manager].delegate = nil;

}

- (void)donePress {
    if (self.ReloadHandle) {
        self.ReloadHandle(dataMutArr);
    }
    [self goBackAction];
}


- (IBAction)deletePress {
//    CustomAlertView *alertView = [[CustomAlertView alloc] initItem:@"确定要删除该音频？" withButtons:[NSArray arrayWithObjects:@"取消", @"确定", nil]];
//    alertView.SureHandle = ^{
//        if (self.DeleteHandle) {
//            self.DeleteHandle(self.model);
//        }
//    };
//    [alertView backgroundClickDisable];
//    [alertView show];
    
    if (dataMutArr.count == 1) {
        [self showHUDAlert:@"至少保留一段音频"];
        return;
    }
    CustomAlertView *alertView = [[CustomAlertView alloc] initItem:@"确定要删除该音频？" withButtons:[NSArray arrayWithObjects:@"取消", @"确定", nil]];
    alertView.SureHandle = ^{
        [self->dataMutArr removeObject:self->selectModel];
        if (self->dataMutArr.count == 1) {
            self.deleteBtn.hidden = YES;
        }
        self->selectModel = [self->dataMutArr firstObject];
        self->selectModel.isSelected = YES;
        [self seeAudio:self->selectModel];
        [self refreshCollectionViewFrame];
        [self.collectionView reloadData];
    };
    [alertView backgroundClickDisable];
    [alertView show];
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [[AVPlayerManager manager] pause];
    } else {
        [[AVPlayerManager manager] play];
    }
}

- (IBAction)cutPress {
    if (currentTime == 0) {
        [self showHUDAlert:@"时间必须大于0秒"];
        return;
    }
    [self loadingHUDAlert];
    
    NSString *path = @"";
    if (selectModel.needSaveUrl) {
        path = [selectModel.needSaveUrl absoluteString];
    } else {
        path = [[FileManager sharedManager] getLocalFilePath:selectModel.fileName];
    }
    [AVPlayerManager splitAudioTime:currentTime withPath:path completed:^(NSString *path1, NSString *path2) {
        LocalRecordModel *localModel1 = [[LocalRecordModel alloc] initRecord:@"m4a"];
        localModel1.needSaveUrl = [NSURL fileURLWithPath:path1];
        localModel1.nickName = [NSString stringWithFormat:@"%@-拆分1", self->selectModel.nickName];
        localModel1.isSelected = YES;
        
        sleep(1.0);
        
        LocalRecordModel *localModel2 = [[LocalRecordModel alloc] initRecord:@"m4a"];
        localModel2.needSaveUrl = [NSURL fileURLWithPath:path2];
        localModel2.nickName = [NSString stringWithFormat:@"%@-拆分2", self->selectModel.nickName];
        
        NSInteger index = [self->dataMutArr indexOfObject:self->selectModel];
        [self->dataMutArr replaceObjectAtIndex:index withObject:localModel1];
        self->selectModel = localModel1;
        [self seeAudio:localModel1];
        
        [self->dataMutArr insertObject:localModel2 atIndex:index+1];
        __weak __typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf refreshCollectionViewFrame];
            [weakSelf.collectionView reloadData];
            weakSelf.deleteBtn.hidden = NO;
        });
    }];
    
}

- (void)seeAudio:(LocalRecordModel *)model {
    NSURL *url = nil;
    if (model.needSaveUrl) {
        url = model.needSaveUrl;
    } else {
        url = [NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:selectModel.fileName]];
    }
    [[AVPlayerManager manager] pause];
    [self trackPlayDidEnd];
    [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [[AVPlayerManager manager] setAVPlayerURL:url];
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    duration = CMTimeGetSeconds(asset.duration);
    __weak __typeof(self) weakSelf = self;
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
            imgv.image = spectrumImage;
            [weakSelf.waveScrollView addSubview:imgv];
            UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
            scaleImgv.image = scaleImage;
            [weakSelf.waveScrollView addSubview:scaleImgv];
            
        });
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [[AVPlayerManager manager] pause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];

//    [[AVPlayerManager manager] play];
//    self.actionBtn.selected = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView == scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*duration;
        if (currentTime > duration) {
            currentTime = duration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

#pragma mark ---AVPlayerDelegate---
- (void)timeRunAndTime:(double)runTime andValue:(NSString *)value andScale:(CGFloat)scale {
    currentTime = runTime;
    self.timeLabel.text = value;
    if ([AVPlayerManager manager].isPlaying) {
        CGFloat pointX = (self.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
        if (pointX < self.waveScrollView.contentOffset.x) {
            pointX = self.waveScrollView.contentOffset.x;
        }
        [UIView animateWithDuration:0.1 animations:^{
            [self.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
        }];
    }
}

- (void)trackPlayDidEnd {
    self.actionBtn.selected = NO;
    [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}


- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 50 - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];
    [self configCollectionView];

}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return dataMutArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * CellIdentifier = @"RecordEditSpectrumCell";
    RecordEditSpectrumCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if (dataMutArr.count == 1) {
        cell.onlyOneData = YES;
    } else {
        cell.onlyOneData = NO;
    }
    cell.indexRow = indexPath.row;
    cell.model = [dataMutArr objectAtIndex:indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LocalRecordModel *model = [dataMutArr objectAtIndex:indexPath.row];
    if (model != selectModel) {
        NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:[dataMutArr indexOfObject:selectModel] inSection:0];
        selectModel.isSelected = NO;
        model.isSelected = YES;
        selectModel = model;
        [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:indexPath, oldIndexPath, nil]];
        [self seeAudio:selectModel];
    }
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    LocalRecordModel *model = [dataMutArr objectAtIndex:sourceIndexPath.row];
    [dataMutArr removeObject:model];
    [dataMutArr insertObject:model atIndex:destinationIndexPath.row];
    [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:sourceIndexPath, destinationIndexPath, nil]];
}

- (void)configCollectionView {
    [self refreshCollectionViewFrame];
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[RecordEditSpectrumCollectionViewCell class] forCellWithReuseIdentifier:@"RecordEditSpectrumCell"];
    UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    [self.collectionView addGestureRecognizer:longPresssGes];
}

- (void)refreshCollectionViewFrame {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    if (dataMutArr.count == 1) {
        layout.itemSize = CGSizeMake(SCREEN_WIDTH_DEVICE - 32, 85);
    } else {
        layout.itemSize = CGSizeMake(122, 85);
    }
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 16, 0, 16);
    self.collectionView.collectionViewLayout = layout;
}

- (void)longPressMethod:(UILongPressGestureRecognizer *)longPressGes {
    // 判断手势状态
    switch (longPressGes.state) {
        case UIGestureRecognizerStateBegan: {
            // 判断手势落点位置是否在路径上(长按cell时,显示对应cell的位置,如path = 1 - 0,即表示长按的是第1组第0个cell). 点击除了cell的其他地方皆显示为null
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPressGes locationInView:self.collectionView]];
            // 如果点击的位置不是cell,break
            if (nil == indexPath) {
                break;
            }
            NSLog(@"%@",indexPath);
            // 在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:
            // 移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longPressGes locationInView:self.collectionView]];
            break;
        case UIGestureRecognizerStateEnded:
            // 移动结束后关闭cell移动
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}
@end
